package org.example.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.example.Constants;
import org.example.Spliter;
import org.example.codec.PacketDecoder;
import org.example.codec.PacketEncoder;

public class ServerBoostrap {
    public static void main(String[] args) {

        // 服务端引导器
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        // 线程组
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();

        // 绑定
        serverBootstrap
                // 线程模型
                .group(boss, worker)
                // IO模型
                .channel(NioServerSocketChannel.class)
                // 处理器数据处理等
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new Spliter());
                        ch.pipeline().addLast(new PacketDecoder());
                        ch.pipeline().addLast(new LoginRequestHandler());
                        // 服务端增加认证处理器
                        ch.pipeline().addLast(new AuthHandler());
                        ch.pipeline().addLast(new MessageRequestHandler());
                        // 增加创建群组处理器
                        ch.pipeline().addLast(new CreateGroupRequestHandler());
                        ch.pipeline().addLast(new JoinGroupRequestHandler());
                        ch.pipeline().addLast(new QuitGroupRequestHandler());
                        ch.pipeline().addLast(new MemberGroupRequestHandler());
                        ch.pipeline().addLast(new PacketEncoder());
                    }
                });

        // 端口绑定
        serverBootstrap.bind(Constants.port).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("服务端启动成功.");
            }else {
                // 重新绑定，端口递增尝试绑定
                System.out.println("服务端启动失败.重新绑定新端口..");
                bind(serverBootstrap, Constants.port);
            }
        });
    }

    private static void bind(ServerBootstrap serverBootstrap, int port) {
        serverBootstrap.bind(port).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("服务端启动成功.端口为：" + port);
            }else {
                // 重新绑定，端口递增尝试绑定
                System.out.println("服务端启动失败.重新绑定端口: " + (port));
                bind(serverBootstrap, port);
            }
        });
    }
}
